package repository

import (
	"apiGateWay/internal/model"
	"gorm.io/gorm"
)

// ConfigRepository 配置仓库接口
type ConfigRepository interface {
	GetByKey(key string) (*model.SystemConfig, error)
	GetByCategory(category string) ([]*model.SystemConfig, error)
	CreateOrUpdate(config *model.SystemConfig) error
	Delete(key string) error
}

type configRepository struct {
	db *gorm.DB
}

// NewConfigRepository 创建配置仓库
func NewConfigRepository(db *gorm.DB) ConfigRepository {
	return &configRepository{db: db}
}

func (r *configRepository) GetByKey(key string) (*model.SystemConfig, error) {
	var config model.SystemConfig
	err := r.db.Where("key = ?", key).First(&config).Error
	if err != nil {
		return nil, err
	}
	return &config, nil
}

func (r *configRepository) GetByCategory(category string) ([]*model.SystemConfig, error) {
	var configs []*model.SystemConfig
	err := r.db.Where("category = ?", category).Find(&configs).Error
	return configs, err
}

func (r *configRepository) CreateOrUpdate(config *model.SystemConfig) error {
	var existing model.SystemConfig
	err := r.db.Where("key = ?", config.Key).First(&existing).Error
	if err == gorm.ErrRecordNotFound {
		return r.db.Create(config).Error
	} else if err != nil {
		return err
	}
	config.ID = existing.ID
	return r.db.Save(config).Error
}

func (r *configRepository) Delete(key string) error {
	return r.db.Where("key = ?", key).Delete(&model.SystemConfig{}).Error
}


